/**
 * Copyright(c) 2014 Xunton Solutions
 *
 * History:
 *   15-1-18 下午7:42 Created by dwzhang
 */
package com.jade.modules.template.impl;

import java.util.List;
import javax.inject.Named;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;

import com.jade.framework.base.criterion.Criteria;
import com.jade.framework.base.criterion.sql.SqlUtils;
import com.jade.framework.base.util.PagingList;
import com.jade.modules.template.Template;
import com.jade.modules.template.TemplateDao;
import com.jade.modules.template.TemplateException;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.cache.annotation.Caching;

/**
 * 采用JPA方式实现的模版数据接口。
 *
 * @author <a href="mailto:dwzhang@xunton.com">dwzhang</a> 
 * @version 1.0 15-1-18 下午7:42
 */
//@Named ("module_templateDao")
public class JpaTemplateDao implements TemplateDao
{
    @PersistenceContext (unitName = "default")
    protected EntityManager entityManager;

    @Caching (evict = {@CacheEvict (value = "module.template.g", key = "#template.id"),
            @CacheEvict (value = "module.template.l", allEntries = true),
            @CacheEvict (value = "module.template.q", allEntries = true)})
    public void add(Template template)
            throws TemplateException
    {
        entityManager.persist(template);
    }

    @Caching (evict = {@CacheEvict (value = "module.template.g", key = "#template.id"),
            @CacheEvict (value = "module.template.l", allEntries = true),
            @CacheEvict (value = "module.template.q", allEntries = true)})
    public void update(Template template)
            throws TemplateException
    {
        entityManager.merge(template);
    }

    @Caching (evict = {@CacheEvict (value = "module.template.g", key = "#template.id"),
            @CacheEvict (value = "module.template.l", allEntries = true),
            @CacheEvict (value = "module.template.q", allEntries = true)})
    public void remove(Template template)
            throws TemplateException
    {
        Template old = entityManager.find(Template.class, template.getId());
        if (old != null) {
            entityManager.remove(old);
        }
    }

    @Cacheable (value = "module.template.g", key = "#id")
    public Template get(long id)
    {
        return entityManager.find(Template.class, id);
    }

    @Cacheable (value = "module.template.l", key = "#criteria")
    public List<Template> list(Criteria criteria)
    {
        return SqlUtils.sqlQueryWithoutCount(SQL_TEMPLATE, entityManager, criteria);
    }

    @Cacheable (value = "module.template.q", key = "#criteria")
    public PagingList<Template> query(Criteria criteria)
    {
        return SqlUtils.sqlQuery(SQL_TEMPLATE, entityManager, criteria);
    }

    protected static final String SQL_TEMPLATE = "SELECT template FROM com.jade.modules.template.Template template";
}
